const express = require("express");
const app = express();
const port = 3000;
const bodyParser = require("body-parser");
const cors = require("cors");
const userRouter = require("./router/userRoute");

app.use(cors());
app.use(bodyParser.json());
const authMiddleware = (req, res, next) => {
  if (req.url === "/login") {
    next();
    return;
  }
  const authHeader = req.headers.authorization;
  if (!authHeader || !authHeader.startsWith("Bearer ")) {
    if (req.url === "/login") {
      next();
      return;
    } else {
      return res.status(200).json({ status: false, message: "未提供访问令牌" });
    }
  
}
  const token = authHeader.split(" ")[1];
  try {
    const decoded = jwt.verify(token, scurityKey); // 验证令牌
    req.user = decoded; // 将解码后的用户信息附加到请求对象
    next();
  } catch (error) {
    if (req.url === "/login") {
      next();
      return;
    }
    res.status(200).json({ status: false, message: "无效令牌" });
  }
};
// 路由
app.use("/api/user", authMiddleware, userRouter);

// 启动服务器
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});
